package com.chenjiaru.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chenjiaru.util.entity.mapping.Mapping;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.common.xcontent.XContentType;

import java.io.IOException;

/**
 * es索引库操作的工具类
 */
@Slf4j
public class ElasticSearchIndexUtil {


    /**
     * 创建索引
     * @param index     索引名称
     */
    public static void deleteIndex(String index) throws IOException {
        log.warn("删除{}索引库", index);
        org.elasticsearch.client.RestHighLevelClient client = RestHighLevelClient.getInstance();
        DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest(index);
        AcknowledgedResponse acknowledgedResponse = client.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
        log.warn("acknowledged={}", acknowledgedResponse.isAcknowledged());
    }


    /**
     * 创建索引
     * @param index          索引名称
     * @param mapping       json字符串的
     * @throws IOException
     */
    public static void createIndex(String index, Mapping mapping) throws IOException {
        log.warn("创建{}索引库", index);
        org.elasticsearch.client.RestHighLevelClient client = RestHighLevelClient.getInstance();
        CreateIndexRequest createIndexRequest = new CreateIndexRequest(index);
        JSONObject mappingJSONObject = (JSONObject) JSON.toJSON(mapping);
        log.warn("mapping={}", mappingJSONObject);
        createIndexRequest.mapping(mappingJSONObject.toJSONString(), XContentType.JSON);
        CreateIndexResponse createIndexResponse = client.indices().create(createIndexRequest, RequestOptions.DEFAULT);
        log.warn("acknowledged={}", createIndexResponse.isAcknowledged());
    }

}
